let mongoose = require("mongoose")
mongoose.set("useCreateIndex", true)

let DB_NAME = "demo"
let DB_URL = "localhost:27017"

let dbPromise = new Promise((resolve, reject) => {
    mongoose.connect(`mongodb://${DB_URL}/${DB_NAME}`, {useNewUrlParser: true})
    mongoose.connection.on("open", (err) => {
        if(!err){
            console.log("数据库连接成功!")
            resolve()
        }else{
            console.log(err)
            reject(err)
        }
    })
})

;(async() => {
    await dbPromise
       
    let Schema = mongoose.Schema
    let studentSchema = new Schema({
        stu_id: {
            type: String,
            require: true,
            unique: true
        },
        name: {
            type: String,
            require: true,
        },
        age: {
            type: Number,
            require: true,
        },
        sex: {
            type: String,
            require: true
        },
        hobby: [String],
        info: {
            type: Schema.Types.Mixed
        },
        date: {
            type: Date,
            default: Date.now()
        },
        enable_flag: {
            type: String,
            default: "Y",
        }
    })

    let studentModel = mongoose.model("students", studentSchema)
    studentModel.find({age: 18}, (err, data) => {
        if(!err){
            console.log(data)
        }else{
            console.log(err)
        }
    })

    // 返回Promise实例
    var result = await studentModel.find({name: "立夏"}, {name: 1, hobby: 1, _id: 0})
    console.log(result)

    // 更新数据
    let updateResult = await studentModel.updateMany({age: 20}, {enable_flag: "N"})
    console.log(updateResult)
})()